<template>
  <div>
    <el-steps :active="active" align-center>
      <el-step v-if="uploadTag" title="填写基础数据" />
      <el-step title="上传模版数据" />
      <el-step title="模版数据检测" />
      <el-step title="单据建立完成" />
    </el-steps>
    <div class="step-two">
      <div v-if="uploadTag && active == 1">
        <el-form ref="rulesForm" label-position="top" label-width="130px" :model="form" :rules="rules">
          <div class="flex_">
            <el-form-item label="客户名称：" prop="CUSTOMER_NAME">
              <el-input v-model="form.CUSTOMER_NAME" />
            </el-form-item>
            <el-form-item label="业务类型：" prop="BUSINESS_TYPE">
              <el-select v-model="form.BUSINESS_TYPE" clearable placeholder="请选择">
                <el-option v-for="item in budgetUnit.businessType" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="温度类型：" prop="TEMPERATURE_TYPE">
              <el-select v-model="form.TEMPERATURE_TYPE" clearable placeholder="请选择">
                <el-option v-for="item in budgetUnit.temperatureType" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </div>
          <div class="flex_">
            <el-form-item label="场地规模：" prop="PLACE_SCALE">
              <el-select v-model="form.PLACE_SCALE" clearable placeholder="请选择">
                <el-option v-for="item in budgetUnit.fieldScale" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="建设类型：" prop="CONSTRUCTION_TYPE">
              <el-select v-model="form.CONSTRUCTION_TYPE" clearable placeholder="请选择">
                <el-option v-for="item in budgetUnit.constructionType" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="能否实现封闭式：" prop="BE_CLOSED">
              <el-select v-model="form.BE_CLOSED" clearable placeholder="请选择">
                <el-option v-for="item in budgetUnit.closed" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </div>
          <div class="flex_">
            <el-form-item label="配置类型：" prop="CONFIGURATION_TYPE">
              <el-select v-model="form.CONFIGURATION_TYPE" clearable placeholder="请选择">
                <el-option v-for="item in budgetUnit.configType" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="外购设备池：" prop="CONFIGURATION_TYPE">
              <el-select v-model="form.OUT_SOURCE_POOL_NAME" clearable placeholder="请选择">
                <el-option
                  v-for="item in poolopOption"
                  :key="item.OUT_SOURCE_POOL_NAME"
                  :label="item.OUT_SOURCE_POOL_NAME"
                  :value="item.OUT_SOURCE_POOL_NAME"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="优先级：" prop="PRIORITY">
              <el-radio-group v-model="form.PRIORITY">
                <el-radio-button label="紧急" />
                <el-radio-button label="一般" />
                <el-radio-button label="不急" />
              </el-radio-group>
            </el-form-item>
          </div>
          <el-form-item label="备注：">
            <el-input v-model="form.NOTES" maxlength="300" placeholder="请输入内容" :rows="6" show-word-limit type="textarea" />
          </el-form-item>
          <div class="footer_">
            <el-form-item>
              <el-button @click="$emit('cancel')">取消</el-button>
              <el-button type="primary" @click="submitForm">下一步</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div v-else-if="(uploadTag && active == 2) || (!uploadTag && active == 1)">
        <div class="hint_">
          <p class="hint-title">特别提示</p>
          <p class="hint-explain">请使用系统要求模板按格式要求填写数据，填写完成进行数据上传</p>
        </div>
        <div class="box_">
          <div class="left-box"></div>
          <div>
            <p>填写导入数据信息</p>
            <p>请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除</p>
            <el-button type="text" @click="download">下载模板</el-button>
          </div>
        </div>
        <div class="box_">
          <div class="left-box"></div>
          <vui-upload
            ref="fileUploadRef"
            class="text-left"
            :file-name="uploadOptions.name"
            :limit="1"
            :post-data="uploadOptions.postData"
            :url="uploadOptions.url"
            @uploadSuccess="uploadSuccess"
          >
            <div>
              <p>上传填好的信息表</p>
              <p>文件后缀名必须为xls或xlsx(Excel格式)，文件大小不得大于10M</p>
              <el-button v-if="!file" size="small" type="text">上传文件</el-button>
            </div>
          </vui-upload>
        </div>
        <div class="footer_">
          <el-button v-if="uploadTag" @click="lastStepTwo">上一步</el-button>
          <el-button v-else @click="$emit('cancel')">取消</el-button>
          <el-button type="primary" @click="clickUpload">下一步</el-button>
        </div>
      </div>
      <div v-else-if="(uploadTag && active == 3) || (!uploadTag && active == 2)">
        <div v-if="abnormal">
          <div class="box_" style="height: 80px">
            <div class="left-box"></div>
            <div>
              <p>
                正常数量条数：
                <span>{{ errorData.successNumber }}</span>
              </p>
              <p>
                异常数量条数：
                <span style="color: red">{{ errorData.failNumber }}</span>
              </p>
            </div>
          </div>
          <div class="abnormal-hint">
            <p>异常提示</p>
            <template v-for="(item, index) in errorData.errorInfoList" :key="index">
              <p style="color: red">
                {{ item }}
              </p>
            </template>
          </div>
          <div class="footer_">
            <el-button @click="lastStepThree">返回上一步，重新上传</el-button>
          </div>
        </div>
      </div>
      <div v-else-if="(uploadTag && active == 4) || (!uploadTag && active == 3)" class="success">
        <div>
          <p v-if="!uploadTag">数据导入成功</p>
          <div v-else>
            <p>
              您本次的预算单单号为：
              <el-button type="text" @click="toDetails">{{ formEnd.DOCNO }}</el-button>
            </p>
            <el-button type="primary" @click="addNew">创建新预算单</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import { defineComponent } from 'vue'
  import requestMethod from '../common/requestMethod'
  import publicFn from '../common/requestCommon'
  import budgetUnit from '../common/options'
  import { GFCD } from '@/utils/utils'
  import { download } from '../api/home'
  const configSetting = GFCD('bqms')
  export default defineComponent({
    name: 'UploadDialog',
    props: {
      uploadTag: {
        type: String,
        default: '',
      },
    },
    emits: ['cancel', 'success'],
    data() {
      return {
        uploadOptions: {
          postData: {
            method: requestMethod.FILE_IMPORT,
            data: '{"TEMP_TYPE":"BUDGET"}',
          },
          name: 'uploadFile',
          url: `${configSetting.domain}${configSetting.baseUrl}`,
        },
        budgetUnit,
        tablePage: {
          '#LIMIT#': 1,
          '#PAGE_SIZE#': 9999,
        },
        poolopOption: [],
        active: 1,
        formEnd: {
          DOCNO: '',
        },
        abnormal: false,
        form: {
          NOTES: '',
        },
        errorData: {},
        rules: {
          CUSTOMER_NAME: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
          BUSINESS_TYPE: [{ required: true, message: '请选择业务类型', trigger: 'change' }],
          TEMPERATURE_TYPE: [{ required: true, message: '请选择温度类型', trigger: 'change' }],
          PLACE_SCALE: [{ required: true, message: '请选择场地规模', trigger: 'change' }],
          CONSTRUCTION_TYPE: [{ required: true, message: '请选择建设类型', trigger: 'change' }],
          BE_CLOSED: [{ required: true, message: '请选择能否实现封闭式', trigger: 'change' }],
          CONFIGURATION_TYPE: [{ required: true, message: '请选择配置类型：', trigger: 'change' }],
          OUT_SOURCE_POOL_NAME: [{ required: true, message: '请选择外购设备池：', trigger: 'change' }],
          PRIORITY: [{ required: true, message: '请选择优先级：', trigger: 'change' }],
        },
      }
    },
    created() {
      if (this.uploadTag) {
        this.formEnd.ACTION = 'QUOTATION_FIRST'
      } else {
        this.formEnd.ACTION = 'QUOTATION_REPEAT'
      }
      this.getOption()
    },
    methods: {
      async getOption() {
        let res = await publicFn(requestMethod.OUTSOURCING_OPTION, { '#LIMIT#': 1, '#PAGE_SIZE#': 99999 })
        console.log(res)
        if (res.code == '00000') {
          this.poolopOption = res.data[requestMethod.OUTSOURCING_OPTION].data
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      async to() {
        if (this.active == 4 || (!this.uploadTag && this.active == 3)) return
        this.active++
      },
      //步骤二的上一步
      async lastStepTwo() {
        let res = await publicFn(requestMethod.DELETE_SINGLE_HEAD, { DOCNO: this.formEnd.DOCNO })
        if (res.code === '00000') {
          this.active--
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      toDetails() {},
      addNew() {
        this.active = 1
        this.form = {
          NOTES: '',
        }
        this.formEnd = {
          DOCNO: '',
        }
        this.abnormal = false
        this.form = {
          NOTES: '',
        }
        this.errorData = {}
      },
      async lastStepThree() {
        let res = await publicFn(requestMethod.DELETE_IMPORT, { DOCNO: this.formEnd.DOCNO })
        if (res.code === '00000') {
          this.active--
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      async threeNext() {
        if (!this.formEnd.DOCNO) {
          this.formEnd.DOCNO = this.$store.getters['bqmsData/budgetSheetNum']
        }
        console.log(this.formEnd)
        let res = await publicFn(requestMethod.IMPORT_SP, this.formEnd)
        if (res.code === '00000') {
          this.active++
          this.$emit('success')
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      //新增弹头表单
      async getBudget() {
        let res = await publicFn(requestMethod.BUDGET_HEADER_ADD, { ...this.form })
        if (res.code === '00000') {
          //初始创建单号
          if (this.uploadTag) {
            this.formEnd.DOCNO = res.data[0].DOCNO
          }
          //此接口成功后才进入下一步
          let res1 = await publicFn(requestMethod.QUOTATION_DROP, {})
          if (res1.code === '00000') {
            this.active++
          } else {
            this.$message({
              type: 'info',
              message: res1.msg,
            })
          }
        } else {
          this.$message({
            type: 'info',
            message: res.msg,
          })
        }
      },
      clickUpload() {
        if (this.$refs['fileUploadRef'].allImgNum) {
          this.$refs['fileUploadRef'].submitUpload()
        } else {
          this.$message({
            type: 'error',
            message: '请选择文件',
          })
        }
      },
      async download() {
        let res = await download(`${configSetting.domain}${configSetting.baseUrl}`, {
          method: requestMethod.TEMPLATE_DOWNLOAD,
          data: JSON.stringify({ TEMP_TYPE: 'BUDGET' }),
        })
        let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        let reader = new FileReader()
        reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = '预算清单模板.xlsx'
          a.href = e.target.result
          a.click()
        }
      },
      twoNext() {
        this.active++
      },
      submitForm() {
        this.$refs['rulesForm'].validate((valid) => {
          if (valid) {
            this.getBudget()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      uploadSuccess(file) {
        let res = file.fileList[0].response
        if (res.code === '00000') {
          this.formEnd.FILE_PATH = res.data.filePath
          this.formEnd.FILE_NAME = res.data.fileName
          this.formEnd.FILE_HIS_NAME = res.data.originalFileName
          this.active++
          this.abnormal = false
          this.threeNext()
        } else if (res.code === 'S0055') {
          this.errorData.successNumber = res.count
          this.errorData.failNumber = res.data.length
          this.errorData.errorInfoList = res.data
          this.$message({
            type: 'error',
            message: res.msg,
          })
          this.abnormal = true
          this.active++
        } else {
          this.$message({
            type: 'error',
            message: res.msg,
          })
        }
      },
    },
  })
</script>
<style lang="scss" scoped>
  .footer_ {
    margin-top: 20px;
    text-align: center;
  }
  .flex_ {
    display: flex;
    justify-content: space-between;
  }
  .el-select .el-input .el-input__inner,
  .el-radio-group {
    width: 193px !important;
  }
  .hint_ {
    background: #fff5e6;
    padding: 15px 30px;
    box-sizing: border-box;
    .hint-title {
      font-weight: 600;
    }
    .hint-explain {
      margin-top: 10px;
    }
  }
  .step-two {
    margin-top: 20px;
  }
  .box_ {
    margin-top: 20px;
    display: flex;
    align-items: center;
    height: 115px;
    border: 1px solid #d8d3d3;
    p {
      margin-top: 10px;
    }
  }
  .left-box {
    background: #f5f5f5;
    width: 50px;
    height: 100%;
  }
  .abnormal-hint {
    padding: 15px;
    margin-top: 20px;
    box-sizing: border-box;
    border: 1px solid #f5f5f5;
    p {
      margin-top: 10px;
    }
  }
  .success {
    display: flex;
    justify-content: center;
    align-items: center;
    & > div {
      height: 300px;
    }
  }
</style>
